var express = require('express');
var router = express.Router();

const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')

// 获取博客列表
router.get('/list', function (req, res, next) {
  let author = req.body.author || ''
  let keyword = req.body.keyword || ''

  if (req.query.isadmin) {
    // 自定义日志
    console.log('is admin')
    // 个人主页
    if (req.session.username == null) {
      // 未登录
      console.log('is admin, but no login')
      res.json(
        new ErrorModel('未登录')
      )
      return
    }
    // 强制查询自己的博客
    author = req.session.username
  }

  const result = getList(author, keyword)

  result.then(listData => {
    res.json(
      new SuccessModel(listData)
    )
  })
});

// 获取博客详情
router.get('/detail', function (req, res, next) {
  const { id } = req.query
  const result = getDetail(id)

  result.then(data => {
    res.json(
      new SuccessModel(data)
    )
  })
});

// 新建一篇博客
router.post('/new', loginCheck, function (req, res, next) {
  req.body.author = req.session.username
  const result = newBlog(req.body)

  result.then(data => {
    res.json(
      new SuccessModel(data)
    )
  })
});

// 更新一篇博客
router.post('/update', loginCheck, function (req, res, next) {
  const { id } = req.query
  const result = updateBlog(id, req.body)

  result.then(data => {
    if (data) {
      res.json(
        new SuccessModel('更新博客成功！')
      )
    } else {
      res.json(
        new ErrorModel('更新博客失败...')
      )
    }
    
  })
});

// 删除一篇博客
router.post('/del', loginCheck, function (req, res, next) {
  const { id } = req.query
  req.body.author = req.session.username
  const result = delBlog(id, req.body.author)

  result.then(data => {
    if (data) {
      res.json(
        new SuccessModel('删除博客成功！')
      )
    } else {
      res.json(
        new ErrorModel('删除博客失败...')
      )
    }
    
  })
});

module.exports = router;
